package com.simple.apt.processor;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import com.google.auto.service.AutoService;
import com.simple.annotation.apt.Simpler;

import javax.annotation.processing.Processor;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.ElementFilter;
import javax.persistence.Id;
import java.util.Objects;

/**
 * @author FanXing
 * @date 2023年01月22日 17:57
 */
@SupportedAnnotationTypes({"com.simple.annotation.apt.Simpler"})
@AutoService(Processor.class)
public class DaoProcessor extends BasicProcessor {

    private static final String PATTERN =
            "package {};\n" +
                    "\n" +
                    "import com.simple.core.dao.BaseRepository;\n" +
                    "import org.springframework.stereotype.Repository;\n" +
                    "\n" +
                    "@Repository\n" +
                    "public interface {} extends BaseRepository<{}, {}> {\n" +
                    "}";

    @Override
    protected String initBuilderClassSrc(TypeElement annotatedClass, String packageStr, String builderClassName, String entityClassName) {
        Element id = ElementFilter.fieldsIn(annotatedClass.getEnclosedElements()).stream()
                .filter(element -> Objects.nonNull(element.getAnnotation(Id.class))).findFirst().orElse(null);
//        TODO 父子类字段读取问题，暂时先写死，后续解决BUG
        String idType = "Long";
        if (Objects.nonNull(id)) {
            String idClass = id.asType().toString();
            idType = StrUtil.subAfter(idClass, '.', true);
        }
        return StrFormatter.format(PATTERN, packageStr, builderClassName, entityClassName, idType);
    }

    @Override
    protected String initBuilderClassName(TypeElement annotatedClass, String className) {
        String actual = annotatedClass.getAnnotation(Simpler.class).prefix();
        String prefix = className;
        if (StrUtil.isNotBlank(actual)) prefix = actual;
        return prefix + "Repository";
    }

}
